package tech.yixiyun.framework.kuafu.controller.interceptor;


import tech.yixiyun.framework.kuafu.bean.BeanContext;
import tech.yixiyun.framework.kuafu.bean.annotation.Priority;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * ControllerInterceptor全局管理类
 */
public class InterceptorContext {


    private static final CopyOnWriteArrayList<Class<? extends IControllerInterceptor>> interceptors = new CopyOnWriteArrayList<>();


    /**
     * 注册ControllerInterceptor
     * @param intercetpor
     */
    public static void register(Class<? extends IControllerInterceptor> intercetpor) {
        if (interceptors.contains(intercetpor) == false) {
            interceptors.add(intercetpor);
        }
        if (interceptors.size() > 1) {
            Collections.sort(interceptors, (a, b) -> {
                double aPriority = 0;
                double bPriority = 0;
                Priority priority = a.getDeclaredAnnotation(Priority.class);
                if (priority != null) {
                    aPriority = priority.value();
                }
                priority = b.getDeclaredAnnotation(Priority.class);
                if (priority != null) {
                    bPriority = priority.value();
                }
                return aPriority == bPriority ? 0 : aPriority < bPriority ? 1 : -1;
            });
        }

    }

    /**
     * 移除某个拦截器
     * @param clazz
     */
    public static void unregister(Class clazz) {
        interceptors.removeIf(item -> item == clazz);
    }



    /**
     * 获取所有拦截器 的遍历器
     * @return
     */
    public static Iterator<IControllerInterceptor> getInterceptorIterator() {
        if (interceptors.isEmpty()) {
            return Collections.emptyIterator();
        }
        List<IControllerInterceptor> instances = new ArrayList<>(interceptors.size());
        for (Class<? extends IControllerInterceptor> interceptor : interceptors) {
            instances.add(BeanContext.getBean(interceptor));
        }
        return instances.iterator();
    }

}
